package com.heima.user.filter;

import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@WebFilter(value = "appTokenFilter", urlPatterns = "/*")
public class AppTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        //获取请求头中的用户id
        String userId = httpServletRequest.getHeader("user");
        if (StringUtils.isNoneBlank(userId)) {
            //创建用户对象给id赋值
            ApUser apUser = new ApUser();

            apUser.setId(Integer.valueOf(userId));
            //放入到ThreadLocal中
            AppThreadLocalUtils.setUser(apUser);
        }
        //放行请求
        chain.doFilter(request,response);
    }
}
